package oop;

import java.util.HashSet;

/**
 * @program: DataStructures
 * @description: equals测试
 * @author: GSY
 * @create: 2020-03-31 10:24
 **/
public class EqualsDemo {



    public static void main(String[] args){
        Person p1 = new Person(20,"gsy");
        Person p2 = new Person(20,"gsy");
        Person p3 = new Person(30,"ly");
        Person p4 = new Person(20,"GSN");

        // 新建HashSet对象
        HashSet set = new HashSet();
        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p4);

        // 比较p1 和 p2， 并打印它们的hashCode()
        System.out.printf("p1.equals(p2) : %s; p1(%d) p2(%d)\n", p1.equals(p2), p1.hashCode(), p2.hashCode());
        // 比较p1 和 p4， 并打印它们的hashCode()
        System.out.printf("p1.equals(p4) : %s; p1(%d) p4(%d)\n", p1.equals(p4), p1.hashCode(), p4.hashCode());
        // 打印set
        System.out.printf("set:%s\n", set);
    }
}


class Person{

    private int age;
    private String name;


    public Person(int age,String name){
        this.age = age;
        this.name = name;
    }


    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }


    @Override
    public boolean equals(Object object){

        if (object == null){//判断是否为空
            return false;
        }
        if (this.getClass() != object.getClass()){//判断类型是否相同
            return false;
        }
        if (this == object){//判断是否使同一个对象
            return true;
        }

        Person person = (Person) object;
        return this.getAge() == person.getAge() && this.getName().equals(person.getName());

    }
    @Override
    public int hashCode(){
        int nameHash =  name.toUpperCase().hashCode();
        return nameHash ^ age;

    }




}
